package com.ntanh.mealplanner.main.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.ntanh.mealplanner.base.model.BaseEntity;
import com.ntanh.mealplanner.main.objects.Ingredient;
import com.ntanh.mealplanner.main.objects.Meal;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

/**
 * Created by Anh Nguyen on 2/27/2015.
 */
public class IngredientDao extends BaseDao {

    public IngredientDao(Context context) {
        super(context);
    }

    public ArrayList<Ingredient> getAll(String author) {
        ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
        String query = "SELECT " + "*"
                + " FROM " + DataBaseHelper.INGREDIENT_TABLE;

        Log.d("query", query);
        Cursor cursor = database.rawQuery(query, null);
        while (cursor.moveToNext()) {
            Ingredient ingredient = convertFromCursor(cursor, author);
            ingredients.add(ingredient);
        }
        return ingredients;
    }

    public Ingredient getById(String author, Integer id) {
        Ingredient ingredient = null;
        String query = "SELECT " + "*"
                + " FROM " + DataBaseHelper.INGREDIENT_TABLE
                + " WHERE id = " + id;

        Log.d("query", query);
        Cursor cursor = database.rawQuery(query, null);
        while (cursor.moveToNext()) {
            ingredient = convertFromCursor(cursor, author);
        }
        return ingredient;
    }

    private Ingredient convertFromCursor(Cursor cursor, String author){
        Ingredient ingredient = new Ingredient(author);
        ingredient.setId(cursor.getInt(0));
        try {
            ingredient.setCreatedDate(BaseEntity.dateFormatter.parse(cursor.getString(1)));
        } catch (ParseException e) {
            ingredient.setCreatedDate(null);
        }
        try {
            ingredient.setModifiedDate(BaseEntity.dateFormatter.parse(cursor.getString(2)));
        } catch (ParseException e) {
            ingredient.setModifiedDate(null);
        }
        ingredient.setCreatedBy(cursor.getString(3));
        ingredient.setModifiedBy(cursor.getString(4));
        ingredient.setActive(cursor.getInt(5) == 1);
        ingredient.setDeleted(cursor.getInt(6) == 1);
        ingredient.setSynced(cursor.getInt(7) == 1);
        ingredient.setName(cursor.getString(8));
        ingredient.setImage(cursor.getString(9));
        ingredient.setDescription(cursor.getString(10));
        ingredient.setUnit(cursor.getString(11));

        return ingredient;
    }
}
